package com.ruoyi.message.api.produce.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.exception.BaseException;
import com.ruoyi.common.core.web.component.LocaleMessageSourceHandler;
import com.ruoyi.message.api.produce.IMessageApiService;
import com.ruoyi.message.api.produce.enums.MessageSendRecordStatusEnum;
import com.ruoyi.message.api.produce.enums.MessageTemplateTypeEnum;
import com.ruoyi.message.general.entity.MessageCountry;
import com.ruoyi.message.general.entity.MessageCountryTemplate;
import com.ruoyi.message.general.entity.MessageSendRecord;
import com.ruoyi.message.general.entity.MessageTemplate;
import com.ruoyi.message.general.service.MessageSendService;
import com.ruoyi.message.manage.service.ManageMessageCountryService;
import com.ruoyi.message.manage.service.ManageMessageCountryTemplateService;
import com.ruoyi.message.manage.service.ManageMessageSendRecordService;
import com.ruoyi.message.manage.service.ManageMessageTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class MessageApiServiceImpl implements IMessageApiService {

    private static final String PATTENT = "\\{(.*?)\\}";
    @Autowired
    private ManageMessageTemplateService manageMessageTemplateService;
    @Autowired
    private ManageMessageSendRecordService manageMessageSendRecordService;
    @Autowired
    private ManageMessageCountryService manageMessageCountryService;
    @Autowired
    private ManageMessageCountryTemplateService manageMessageCountryTemplateService;
    @Autowired
    private LocaleMessageSourceHandler sourceHandler;

    @Resource
    private MessageSendService messageSendService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(String projectName, String type, String sender, String receiver, String code, Map<String, String> params) throws BaseException {
        this.sendMessage(projectName, DEFAULT_AREA_CODE, type, sender, receiver, code, params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendMessage(String projectName, String areaCode, String type, String sender, String receiver, String code, Map<String, String> params) throws BaseException {
        if (log.isDebugEnabled()) {
            log.debug("projectName = {}, areaCode = {}, type = {}, sender = {}, receiver = {}, code = {}, params = {}", projectName, areaCode, type, sender, receiver, code, params);
        }
        if (!type.equals(MessageTemplateTypeEnum.SMS_TYPE.getCode()) && !type.equals(MessageTemplateTypeEnum.EMAIL_TYPE.getCode())) {
            throw new BaseException(sourceHandler.getMessage("MESSAGE_TYPE_NOT_EXIST"));
        }
        //直接获取默认模板
        LambdaQueryWrapper<MessageTemplate> messageTemplateLambdaQueryWrapper = Wrappers.lambdaQuery(MessageTemplate.class)
                .eq(MessageTemplate::getProjectName, projectName)
                .eq(MessageTemplate::getType, type)
                .eq(MessageTemplate::getCode, code)
                .eq(MessageTemplate::getLanguageCode, DEFAULT_LANGUAGE_CODE);
        MessageTemplate defaultMessageTemplate = manageMessageTemplateService.getByObj(messageTemplateLambdaQueryWrapper);
        if (defaultMessageTemplate == null) {
            throw new BaseException(sourceHandler.getMessage("NO_DEFAULT_TEMPLATE"));
        }
        MessageTemplate messageTemplate = null;
        //查询国家是否存在
        LambdaQueryWrapper<MessageCountry> messageCountryLambdaQueryWrapper = Wrappers.lambdaQuery(MessageCountry.class)
                .eq(MessageCountry::getAreaCode, areaCode);
        MessageCountry messageCountry = manageMessageCountryService.getByObj(messageCountryLambdaQueryWrapper);
        if (messageCountry == null) {
            //国家不存在直接使用默认模板
            messageTemplate = defaultMessageTemplate;
        } else {
            //国家存在直接查找模板
            LambdaQueryWrapper<MessageCountryTemplate> messageCountryTemplateLambdaQueryWrapper = Wrappers.lambdaQuery(MessageCountryTemplate.class)
                    .eq(MessageCountryTemplate::getCountryId, messageCountry.getId())
                    .eq(MessageCountryTemplate::getTemplateCode, code);
            MessageCountryTemplate messageCountryTemplate = manageMessageCountryTemplateService.getByObj(messageCountryTemplateLambdaQueryWrapper);
            if (messageCountryTemplate == null) {
                //国家未绑定模板直接使用默认模板
                messageTemplate = defaultMessageTemplate;
            } else {
                //使用绑定的模板
                messageTemplateLambdaQueryWrapper.clear();
                messageTemplateLambdaQueryWrapper = Wrappers.lambdaQuery(MessageTemplate.class)
                        .eq(MessageTemplate::getId, messageCountryTemplate.getTemplateId())
                        .eq(MessageTemplate::getProjectName, projectName)
                        .eq(MessageTemplate::getType, type)
                        .eq(MessageTemplate::getCode, code)
                        .eq(MessageTemplate::getLanguageCode, messageCountry.getLanguageCode());
                messageTemplate = manageMessageTemplateService.getByObj(messageTemplateLambdaQueryWrapper);
                if (messageTemplate == null) {
                    messageTemplate = defaultMessageTemplate;
                }
            }
        }
        if (messageTemplate == null) {
            throw new BaseException(sourceHandler.getMessage("NO_DEFAULT_TEMPLATE"));
        }
        String content = generateSmsContent(messageTemplate, params);
        String messageId = new SimpleDateFormat("yyyyMMddHHmmss").format(DateUtil.date().toJdkDate()) + RandomUtil.randomInt(1000, 9999);
        MessageSendRecord messageSendRecord = new MessageSendRecord();
        messageSendRecord.setProjectName(messageTemplate.getProjectName());
        messageSendRecord.setLanguageCode(messageTemplate.getLanguageCode());
        messageSendRecord.setAreaCode(areaCode);
        messageSendRecord.setType(messageTemplate.getType());
        if (messageSendRecord.getType().equals(MessageTemplateTypeEnum.SMS_TYPE.getCode())) {
            messageSendRecord.setChannel(messageTemplate.getChannel());
        }
        messageSendRecord.setSender(StrUtil.isEmpty(sender) ? "系统" : sender);
        messageSendRecord.setReceiver(receiver);
        messageSendRecord.setMessageId(messageId);
        messageSendRecord.setCode(messageTemplate.getCode());
        messageSendRecord.setStatus(MessageSendRecordStatusEnum.SEND.getCode());
        messageSendRecord.setContent(content);
        messageSendRecord.setCreateTime(DateUtil.date().toJdkDate());
        manageMessageSendRecordService.save(messageSendRecord);
        messageSendService.sendMessage(messageId);
    }

    private String generateSmsContent(MessageTemplate messageTemplate, Map<String, String> params) {
        String content = messageTemplate.getContent();
        Pattern compile = Pattern.compile(PATTENT);
        Matcher matcher = compile.matcher(messageTemplate.getContent());
        while (matcher.find()) {
            String var = matcher.group(1);
            if(params.get(var)!=null) {
                content = content.replaceAll("\\{" + var + "}", params.get(var));
            }
        }
        return content;
    }

}
